﻿using System;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ITViet.Domains;
using ITViet.Services;
using ITViet.Web.App_Code;

namespace ITViet.Web.Controls
{
	public partial class OnlineSupport : BaseControl
	{
		#region Events
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack && !Page.IsCallback)
			{
				LoadOnlineSupportInfo();
			}
		}

		protected void rptYahooNick_OnItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{
				ContactInfo contactInfo = (ContactInfo)e.Item.DataItem;
				HtmlImage image = (HtmlImage)e.Item.FindControl("imgSta");
				string isonval = PostData("http://opi.yahoo.com/online?u=" + contactInfo.Value + "&m=t&t=1");
				if (isonval == "01") image.Src = "~/images/yahoo_online.png";
			}
		}
		#endregion

		#region Methods
		private static string PostData(string url)
		{
			HttpWebRequest request = null;
			Uri uri = new Uri(url);
			string result = "";

			request = (HttpWebRequest)WebRequest.Create(uri);
			request.Method = "POST";
			request.ContentType = "application/x-www-form-urlencoded";

			try
			{
				using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
				{
					using (Stream responseStream = response.GetResponseStream())
					{
						using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
						{
							result = readStream.ReadToEnd();
						}
					}
				}
			}
			catch (Exception ex)
			{
				return string.Empty;
			}

			return result;
		}

		private void LoadOnlineSupportInfo()
		{
			rptYahooNick.DataSource = new ContactInfoService().GetByTypeAndLanguage(ContactType.YahooContact, null, true);
			rptYahooNick.DataBind();

			//rptSkypeNick.DataSource = new ContactInfoService().GetByTypeAndLanguage(ContactType.SkypeContact, null, true);
			//rptSkypeNick.DataBind();

			TList<ContactInfo> contactInfos = new ContactInfoService().GetByTypeAndLanguage(ContactType.Hotline, null, true);
			if (contactInfos.Count > 0)
			{
				ltrHotline.Text = contactInfos[0].Value;
			}
		}
		#endregion
	}
}